<template>
  <div class="MyEvents">
    <MainCard v-for="event in events" :key="event"
              :title="event.title"
              :place="event.place"
              :event-data="event.event_data"
              :description="event.description"
              :button-text="'Отменить заявку'"
              :id="event.id" @cardClick="sendNewEvent($event)"/>
  </div>
  <div class="message" v-show="message">
    <div class="toast-container position-fixed bottom-0 end-0 p-3">
      <div id="liveToast" class="toast" role="alert" aria-live="assertive" style="display: block;" aria-atomic="true">
        <div class="toast-header">
          <strong class="me-auto">Emron</strong>
          <small>Только что</small>
          <!--          <button type="button" class="btn-close" data-bs-dismiss="toast" aria-label="Закрыть"></button>-->
        </div>
        <div class="toast-body" style="text-align: left;">
          {{ messageText }}
        </div>
      </div>
    </div>
  </div>
</template>
<script setup>
import MainCard from "../components/MainCard.vue";
import store from "@/store";
import {onMounted, ref} from "vue";
import * as api from "@/api/index";
import {watch} from "vue";

let events = ref(store.getters.getUserEvents);
const token = store.getters.getToken;
const user = store.getters.getUserInfo;

let message = ref(false);
let messageText = ref("");

onMounted(async () => {
  await store.dispatch("actEvents", await token);
  events.value = await store.getters.getUserEvents;
})

watch(token, async () => {
  events.value = store.getters.getUserEvents;
})

const sendNewEvent = async (event) => {
  console.log(token)
  if (token.length < 10) {
    message.value = true
    messageText.value = "Пожалуйста авторизуйтесь";
    setTimeout(() => {
      message.value = false
    }, 2000)
    return
  } else {
    let req = {
      user_id: user.id,
      event_id: event,
      token: token
    }
    let data = await api.delUserOrder(req);
    if (await data.status !== 200) {
      message.value = true;
      messageText.value = "Что-то пошло не так :(";
      setTimeout(() => {
        message.value = false;
      }, 2500)
    } else {
      message.value = true;
      messageText.value = "Запись отменена";
      setTimeout(() => {
        events.value.forEach((item, index) => {
          if (item.id === req.event_id){
            console.log(item.id, req.event_id)
            events.value.splice(index, 1);
            console.log(events.value)
          }
        })
      }, 1500)
      setTimeout(() => {
        message.value = false;

      }, 2500)
    }
  }
}
</script>
<style scoped lang="scss">
.MyEvents {
  padding: 25px;
  padding-top: 0;
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  grid-row-gap: 30px;
}
</style>